import { Component } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-demo-bese64',
  templateUrl: './demo-bese64.component.html',
  styleUrls: ['./demo-bese64.component.less']
})
export class DemoBese64Component {
  constructor(private message: NzMessageService) { }

  /**
   * 文件上传-仅支持图片格式png/jpg...
   * */

  // constructor(private api: UploadFileService) { }

  // public filesdata: Filedata[] = []
  public filesdata: any = [];
  public alarm: string[] = [];
  public fileBase64: string = "";
  public fileBinary: string = "";
  reader = new FileReader();

  getfiledata(event: any) {
    this.filesdata = []
    this.alarm = []
    var getfile = <HTMLInputElement>document.getElementById('file')  //获取html文件上id为“file”的input标签的值

    if (getfile.files) {
      for (var i = 0; i < getfile.files.length; i++) {
        this.transformFile(getfile.files[i])
      }
    }
    // console.log(this.fileBase64)  //可以在浏览器上看到文件转成的base64编码
  }

  getBeseUrl() {
    if (!this.fileBase64) {
      this.message.error(`未选择任何文件`);
      return
    }
    console.log(this.fileBase64)  //可以在浏览器上看到文件转成的base64编码
    console.log(this.filesdata, 'this.filesdata');


  }


  transformFile(getfile: any) {
    let reader = new FileReader();
    reader.readAsDataURL(getfile);
    reader.onload = () => {
      this.fileBase64 = <string>reader.result  //读取该文件base64编码
      this.fileBinary = atob(this.fileBase64.substring(this.fileBase64.indexOf(',') + 1))//将base64转为二进制编码
      let data = {
        fileName: getfile.name,
        fileBinary: this.fileBinary,
        fileBase64: this.fileBase64
      }
      this.filesdata.push(data)
    }
  }

  // public postfile() {            // 传递选中的标题回服务器    
  //   this.api.postimage(this.filesdata).subscribe(() => { });
  // }

  delBeseUrl() {
    this.filesdata = [];
    this.alarm = [];
    this.fileBase64 = "";
    this.fileBinary = "";

    var getfile = <HTMLInputElement>document.getElementById('file')  //获取html文件上id为“file”的input标签的值
    getfile.value = ''; // 清除input 文本框的值

  }

}
